<template>
  <el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" class="password-reset-page" autocomplete="on" label-position="left">
    <div v-if="isLogin" class="title-container">
      <h3 class="title">
        {{ $t('password.title') }}
      </h3>
      <lang-select class="set-language" />
    </div>
    <el-form-item prop="username">
      <span class="svg-container">
        <svg-icon icon-class="user" />
      </span>
      <el-input
        v-model="passwordForm.username"
        :placeholder="$t('login.account')"
        name="username"
        type="text"
        tabindex="1"
        autocomplete="off"
        :readonly="userNameReadOnly"
      />
    </el-form-item>
    <template v-if="passwordForm.phone">
      <el-form-item prop="phone">
        <span class="svg-container">
          <svg-icon icon-class="phone" style="width: 1.3em; height: 1.3em;vertical-align: -0.4em;"/>
        </span>
        <el-input
          ref="phone"
          v-model="passwordForm.phone"
          name="phone"
          type="text"
          tabindex="1"
          autocomplete="off"
          :readonly="true"
        />
      </el-form-item>
      <el-form-item prop="verificationCode">
        <span class="svg-container">
          <svg-icon icon-class="code" style="width: 1.3em;height: 1.3em;vertical-align: -0.4em;" />
        </span>
        <el-input
          ref="verificationCode"
          v-model="passwordForm.verificationCode"
          :placeholder="$t('password.verificationCode')"
          type="text"
          maxlength="4"
          tabindex="1"
          autocomplete="off"
          style="width: 50%" />
        <el-button icon="el-icon-mobile-phone" style="width: 36%" class="verify-btn" :disabled="!show" :loading="codeLoading" type="text" @click="sendVerify" >
          <span v-show="show">获取验证码</span>
          <span v-show="!show">{{ count }} s</span>
        </el-button>
      </el-form-item>
      <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input
            :key="passwordType"
            v-model="passwordForm.password"
            ref="password"
            :type="passwordType"
            :placeholder="$t('login.password')"
            name="password"
            tabindex="2"
            autocomplete="off"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
      </el-tooltip>
    </template>
    <el-button :loading="passwordLoading" type="primary" style="width:100%;" @click.native.prevent="handlePassword">
      {{ passwordForm.phone ? $t('password.passwordReset') : $t('password.getPhone') }}
    </el-button>
    <p v-if="isLogin" class="forget-password"><span @click.stop.prevent="handlePasswordReset">{{ $t('login.logIn') }}</span></p>
  </el-form>
</template>

<script>
import LangSelect from '@/components/LangSelect'
import { validPassword } from '@/utils/validate'
const validateUsername = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入账号/工号!'))
  } else {
    callback()
  }
}
export default {
  name: 'PasswordReset',
  components: { LangSelect },
  data() {
    return {
      capsTooltip: false,
      passwordForm: {
        username: '',
        phone: '',
        verificationCode: '',
        password: ''
      },
      passwordType: 'password',
      passwordRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        verificationCode: [{ required: true, trigger: 'blur', message: '请输入验证码' }],
        password: [{ required: true, trigger: 'blur', validator: validPassword }]
      },
      passwordLoading: false,
      codeLoading: false,
      show: true,
      count: '',
      timer: null,
      timeCount: 60
    }
  },
  props: {
    isLogin: {
      type: Boolean,
      default: false
    },
    userNameVal: {
      type: String,
      default: ''
    }
  },
  computed: {
    userNameReadOnly() {
      return this.userNameVal ? true : false
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initPasswordForm()
    })
  },
  beforeDestroy() {
    this.initPasswordForm()
    this.$refs.passwordForm.clearValidate()
    clearInterval(this.timer)
    this.timer = null
  },
  methods: {
    initPasswordForm() {
      this.passwordForm = {
        username: this.userNameVal || '',
        phone: '',
        verificationCode: '',
        password: ''
      }
    },
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if (shiftKey && (key >= 'a' && key <= 'z') || !shiftKey && (key >= 'A' && key <= 'Z')) {
          this.capsTooltip = true
        } else {
          this.capsTooltip = false
        }
      }
      if (key === 'CapsLock' && this.capsTooltip === true) {
        this.capsTooltip = false
      }
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handlePassword() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          this.passwordLoading = true
          if (!this.passwordForm.phone) {
            this.$store.dispatch('user/verifyPhone', this.passwordForm.username).then((res) => {
              this.passwordForm.phone = res.data
              if (!res.data) {
                this.$message({
                  message: '请联系管理员录入手机号码！',
                  type: 'warning',
                  duration: 2 * 1000
                })
              }
            }).finally(() => {
              this.passwordLoading = false
            })
          } else {
            this.$store.dispatch('user/sendPasswordReset', {
              username: this.passwordForm.username,
              code: this.passwordForm.verificationCode,
              password: this.passwordForm.password
            }).then(res => {
              this.$message({
                message: '修改密码成功!',
                type: 'success',
                duration: 2 * 1000
              })
              this.$emit('on-submit-success')
            }).finally(() => {
              this.passwordLoading = false
            })
          }
        } else {
          return false
        }
      })
    },
    sendVerify() {
      this.codeLoading = true
      this.$store.dispatch('user/getVerifyCode', {
        username: this.passwordForm.username,
        smsType: 3
      }).then(res => {
        this.$message({
          message: '发送短信成功！请注意查收验证码',
          type: 'success',
          duration: 2 * 1000
        })
        if (!this.timer) {
          this.count = this.timeCount
          this.show = false
          this.timer = setInterval(() => {
            if (this.count > 0 && this.count <= this.timeCount) {
              this.count--
            } else {
              this.show = true
              clearInterval(this.timer)
              this.timer = null
            }
          }, 1000)
        }
      }).finally(() => {
        this.codeLoading = false
      })
    },
    handlePasswordReset() {
      this.$emit('on-password-reset')
    }
  }
}
</script>
<style lang="scss">
  $text: #515a6e;
  @supports (-webkit-mask: none) and (not (cater-color: $text)) {
    .password-reset-page .el-input input {
      color: $text;
    }
  }
  .password-reset-page {
    .el-form-item--medium .el-form-item__content{
      line-height: 30px;
    }
    .el-button--medium{
      padding: 15px 20px;
      margin-bottom: 20px;
    }
    .verify-btn{
      margin-bottom: 0;
      float: right;
    }
    .el-input {
      display: inline-block;
      height: 30px;
      width: 85%;

      input {
        background: transparent;
        border: 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: $text;
        height: 30px;
        caret-color: $text;

        &:-webkit-autofill {
          box-shadow: 0 0 0px 1000px #fff inset !important;
          -webkit-text-fill-color: #515a6e !important;
        }
      }
    }

    .el-form-item {
      border: 1px solid #dcdee2;
      background: #fff;
      border-radius: 5px;
      color: #515a6e;
    }
  }
</style>
<style lang="scss" scoped>
  $bg:#2d3a4b;
  $dark_gray:#889aa4;
  $light_gray:#eee;
    .tips {
      font-size: 14px;
      color: #fff;
      margin-bottom: 10px;

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    .svg-container {
      padding: 6px 5px 6px 15px;
      color:#515a6e;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
    }

    .title-container {
      position: relative;

      .title {
        font-size: 20px;
        color: #17233d;
        margin: 0px auto 40px auto;
        text-align: center;
        font-weight: bold;
      }

      .set-language {
        color: #515a6e;
        position: absolute;
        top: 3px;
        font-size: 18px;
        right: 0px;
        cursor: pointer;
      }
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }

    .thirdparty-button {
      position: absolute;
      right: 0;
      bottom: 6px;
    }

    @media only screen and (max-width: 470px) {
      .thirdparty-button {
        display: none;
      }
    }
    .forget-password{
      font-size: 14px;
      text-align: right;
      margin-bottom: 20px;
      margin-top: 0;
      span{
        cursor: pointer;
        color: $dark_gray;
        &:hover{
          color: #1890ff;
        }
      }
    }

</style>
